package meetingapplication;

import java.util.Vector;

import tota.middleware.TotaMiddleware;
import tota.tuples.TotaTuple;
import tota.tuples.hop.GradientTuple;
import tuplespace.tuples.Tuple;
import emulator.agent.AbstractAgent;
import emulator.peers.Peer;
import emulator.peers.PeerInterface_ApplicationSide;
import emulator.utils.GenPoint;

public class MeetAgent extends AbstractAgent {
 
 // this is the grup of peer that will try to meet	
 private static final String[] group = new String[]{"P0","P1","P2"};	
	
 private PeerInterface_ApplicationSide peer;
 private TotaMiddleware tota;
 private boolean ingroup = false;
 
 public MeetAgent(PeerInterface_ApplicationSide peer) {
  this.peer = peer;
  tota = new TotaMiddleware(peer);
  
  for(int i=0; i<group.length;i++)
   if(peer.toString().equals(group[i]))
	ingroup = true;
  
  System.out.println(peer.getAddress() + " starting...");
 }
 
 public void step(int time) {
   tota.step(time);
   // nodes that are not in the meeting group run the TOTA middleware, but don't do anything
   if(!ingroup) return;
   
   // inject the meeting tuple
   if(time == 10) {
    TotaTuple t = new GradientTuple();
    t.setContent("<content=meet>"); // this notation is mandatory
    tota.inject(t);
   }
   
   if(time%50==0) {
    // read the local tuple space
    GradientTuple mt = new GradientTuple();
    mt.setContent("<content=meet>");
    // read the local tuple space
    Vector local = tota.read(mt);
    GenPoint destination = getDirection(local);
    move(destination);
   }
   peer.setColor(255, 0, 255);
 }
 
 private GenPoint getDirection(Vector v) {
  
  
  for(int i=0; i<v.size(); i++) {
   	  
  }
  
  return null;
 }
 
 private int speed = 10;
 private void move(GenPoint destination){
  Peer p = (Peer) peer.getRealIdentity();
  GenPoint current = p.getLocation();
  GenPoint next = current.getDirection(destination, speed);
  p.emu.move(p.toString(), next);
 }
 
 // interface method empty implementation
 public synchronized void showAgentFrame() {}
 public synchronized void hideAgentFrame() {peer.shutDown();}
 public synchronized Object getRealIdentity() {return this;}
}